/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RankSocios.java
 *
 * Created on Mar 15, 2011, 8:15:25 PM
 */

package forms;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.RowFilter.Entry;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableRowSorter;
import managers.ManagerReporting;

/**
 *
 * @author nMoncho
 */
public class RankSocios extends javax.swing.JFrame {

    //Atributos para la lista de links
    private TableRowSorter<DefaultTableModel> sorter;
    private ButtonGroup radiosDiasGroup = new ButtonGroup();
    //Para tabla Zebra like
    private static final Color evenColor = new Color(221, 238, 255);
    //UI para el link
    private LinkViewRadioButtonUI ui = new LinkViewRadioButtonUI();
    private int sociosPorPagina = 25;
    private final int paginasLR = 5;
    private int paginaActual = 0;
    
    /** Creates new form RankSocios */
    public RankSocios() {
        initComponents();
        rellenarTabla();
        this.setLocation(200, 200);

        this.sorter = new TableRowSorter<DefaultTableModel>((DefaultTableModel)tablaPuntaje.getModel());
        tablaPuntaje.setRowSorter(sorter);
        
        comboSociosPorPagina.setSelectedIndex(2);
        comboSociosPorPagina.addItemListener(new ItemListener(){
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){
                    if(sociosPorPagina != ((Integer)comboSociosPorPagina.getSelectedItem()).intValue()){
                        sociosPorPagina = ((Integer)comboSociosPorPagina.getSelectedItem()).intValue();
                        makeLinkBox(0);//Volver al inicio
                    }
                }
            }
        });
    }

    private void rellenarTabla(){
        gestor.getReportRankingClientes(tablaPuntaje.getModel());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tablaPuntaje = new javax.swing.JTable(){
            @Override
            public Component prepareRenderer(TableCellRenderer tcr, int row, int column) {
                Component c = super.prepareRenderer(tcr, row, column);
                if(isRowSelected(row)) {
                    c.setForeground(getSelectionForeground());
                    c.setBackground(getSelectionBackground());
                }else{
                    c.setForeground(getForeground());
                    c.setBackground((row%2!=0)?evenColor:getBackground());
                }
                return c;
            }
        };
        botonAceptar = new javax.swing.JButton();
        botonCancelar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        botonFiltrar = new javax.swing.JButton();
        panelLinks = new javax.swing.JPanel();
        labelSociosPorPagina = new javax.swing.JLabel();
        comboSociosPorPagina = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ranking de Socios");
        setIconImage(new ImageIcon(getClass().getResource("/resources/arrow-branch-bgr-16-ns.png")).getImage());

        tablaPuntaje.setIntercellSpacing(new Dimension());
        tablaPuntaje.setShowHorizontalLines(false);
        tablaPuntaje.setShowVerticalLines(false);
        tablaPuntaje.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Legajo", "Nombre", "Cant. Visitas", "Cant. Invitados", "Puntaje Total"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaPuntaje.setToolTipText("Ranking");
        jScrollPane1.setViewportView(tablaPuntaje);

        botonAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/badge-square-check-16-ns.png"))); // NOI18N
        botonAceptar.setText("Aceptar");
        botonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonAceptarActionPerformed(evt);
            }
        });

        botonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/badge-square-cross-16-ns.png"))); // NOI18N
        botonCancelar.setText("Cancelar");
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCancelarActionPerformed(evt);
            }
        });

        jLabel1.setText("Ranking de Socios: ");

        botonFiltrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/note-todo-list-16.png"))); // NOI18N
        botonFiltrar.setText("Filtrar");
        botonFiltrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonFiltrarActionPerformed(evt);
            }
        });

        panelLinks.setLayout(new javax.swing.BoxLayout(panelLinks, javax.swing.BoxLayout.LINE_AXIS));

        labelSociosPorPagina.setText("Socios por Pagina:");

        comboSociosPorPagina.setModel(new javax.swing.DefaultComboBoxModel(new Integer[] { 5, 10, 25, 50 }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 675, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(labelSociosPorPagina)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(comboSociosPorPagina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 341, Short.MAX_VALUE)
                        .addComponent(botonAceptar)
                        .addGap(18, 18, 18)
                        .addComponent(botonCancelar))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(36, 36, 36)
                        .addComponent(panelLinks, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 465, Short.MAX_VALUE)
                        .addComponent(botonFiltrar)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {botonAceptar, botonCancelar});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(botonFiltrar))
                    .addComponent(panelLinks, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonCancelar)
                    .addComponent(botonAceptar)
                    .addComponent(labelSociosPorPagina)
                    .addComponent(comboSociosPorPagina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAceptarActionPerformed
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_botonAceptarActionPerformed

    private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_botonCancelarActionPerformed

    private void botonFiltrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonFiltrarActionPerformed
        if(pantallaFiltros == null || !pantallaFiltros.isDisplayable())
            pantallaFiltros = new FiltrosRanking(gestor);
        
        pantallaFiltros.toFront();
    }//GEN-LAST:event_botonFiltrarActionPerformed

    public JTable getTable(){
        return tablaPuntaje;
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RankSocios().setVisible(true);
            }
        });
    }

    private ManagerReporting gestor = new ManagerReporting(this);
    private FiltrosRanking pantallaFiltros = null;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonAceptar;
    private javax.swing.JButton botonCancelar;
    private javax.swing.JButton botonFiltrar;
    private javax.swing.JComboBox comboSociosPorPagina;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelSociosPorPagina;
    private javax.swing.JPanel panelLinks;
    private javax.swing.JTable tablaPuntaje;
    // End of variables declaration//GEN-END:variables

    public void makeLinkBox(int paginaActual){
        sorter.setRowFilter(makeRowFilter(paginaActual));
        ArrayList<JRadioButton> links = new ArrayList<JRadioButton>();
        int paginaInicio = paginaActual - paginasLR;
        if (paginaInicio < 0) paginaInicio = 0;

        int cantPaginas = (tablaPuntaje.getModel().getRowCount()/sociosPorPagina) +1;
        if(cantPaginas <= 1){//En caso de que haya solo una pagina no mostrar nada
            panelLinks.removeAll();
            panelLinks.revalidate();
            panelLinks.repaint();
            return;
        }

        this.paginaActual = paginaActual;
        int finPagina = paginaActual + paginasLR;
        if (finPagina > cantPaginas) finPagina = cantPaginas;

        if(paginaActual > 0)
            links.add(makeLinkButton(paginaActual-1, "Ant."));
        for(int i= paginaInicio; i<finPagina;i++){
            links.add(makeLinkButton(i));
        }
        if((paginaActual+1) < finPagina)
            links.add(makeLinkButton(paginaActual+1, "Sig."));

        panelLinks.removeAll();
        ButtonGroup bg = new ButtonGroup();
        panelLinks.add(Box.createHorizontalGlue());
        for(JRadioButton r:links) {
            panelLinks.add(r); bg.add(r);
        }
        panelLinks.add(Box.createHorizontalGlue());
        panelLinks.revalidate();
        panelLinks.repaint();
        links.clear();
    }

    /**
     * Filtro por paginas
     * @param pagina pagina que se fitrara
     * @return el objeto RowFilter para filtrar la JTable
     */
    private RowFilter< DefaultTableModel, Integer > makeRowFilter(final int pagina) {
        return new RowFilter< DefaultTableModel, Integer >(){
            @Override
            public boolean include(Entry<? extends DefaultTableModel, ? extends Integer> entry) {
                int ei = entry.getIdentifier();
                return (pagina*sociosPorPagina <= ei && ei < pagina*sociosPorPagina+sociosPorPagina);
            }
        };
    }

    private JRadioButton makeLinkButton(final int linkPagina){
        JRadioButton radio = new JRadioButton(""+(linkPagina+1));
        radio.setForeground(Color.BLUE);
        radio.setUI(ui);
        if(linkPagina == paginaActual) {
            radio.setSelected(true);
            radio.setForeground(Color.BLACK);
        }
        radio.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            makeLinkBox(linkPagina);
          }
        });
        return radio;
    }

    private JRadioButton makeLinkButton(final int linkPagina, String texto){
        JRadioButton radio = new JRadioButton(texto);
        radio.setForeground(Color.BLUE);
        radio.setUI(ui);
        radio.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            makeLinkBox(linkPagina);
          }
        });
        return radio;
    }
}
